package xing.design.pattern.create.factory.abstractFactory.factory;

import xing.design.pattern.create.factory.IBasic;
import xing.design.pattern.create.factory.abstractFactory.IOtherBasic;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * 简单工厂，判断返回~~响~~相应的工厂。
 *
 * 对于不会变的唯一抽象工厂，可以通过配置文件获取。
 *
 * 否则，用这种方式并不会变得简单。传参什么的，为什么不直接自己 new 一个对应工厂呢。
 *
 * @author xing
 * @date 2023/2/7 23:33:01
 */
public class ConfigurableSimpleFactory {
    // 全类名
    private static final String CLASS_NAME;

    // 从配置文件获取
    static {
        Properties properties = new Properties();
        try {
            // 根据  从项目根目录开始的路径，找到文件，获取文件流。
            properties.load(Files.newInputStream(Paths.get("src","xing", "design", "pattern", "create", "factory", "abstractFactory", "config.properties")));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        CLASS_NAME = properties.getProperty("factory.path");
    }

    public static IBasic creatBasic() {
        IBasicFactory factory = getFactory();
        return factory.createBasic();
    }

    public static IOtherBasic createOtherBasic() {
        return getFactory().createOtherBasic();
    }

    public static IBasicFactory getFactory() {
        try {
            return (IBasicFactory) Class.forName(CLASS_NAME).newInstance();
        } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
